#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author:    御风
# @Mail:      zhong.yufeng@foxmail.com
# @Time:      2022/4/12 1:20


import io
import base64
import time
from flask_cors import cross_origin
from utils.captchaer import generateCaptcha
from utils.result import ApiResult
from utils.session.session import Session
from .admin import route


# http://127.0.0.1:9001/admin/captcha
@route.route("/captcha", methods=["GET"], strict_slashes=False)
@cross_origin()
def apiCaptcha():
    """
    管理验证码接口
    """
    session = Session.get()
    code, image = generateCaptcha()
    session["adminCaptchaCode"] = code
    session["adminCaptchaTime"] = int(time.time())
    Session.set(session)

    imgio = io.BytesIO()
    image.save(imgio, "png")
    imgdata = imgio.getvalue()
    data = base64.b64encode(imgdata).decode("utf-8")

    result = {
        "image":   f"data:image/png;base64,{data}",
        "session": Session.serializer()
    }
    return ApiResult.success(result, msg="成功")
